package com.ds.common.org.expression.org;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.org.Org;

 /** 
  * 取得一些组织的直接上级和间接上级的组织（递归）
 * <p>Title: JDSORG组织机构中间件</p>
 * <p>Description: </p>
 * <p>Copyright: jds Copyright (c) 2003-2008</p>
 * <p>Company: www.justdos.net</p>
 * @author wenzhangli
 * @version 2.0
 */
public class GetAllParentOrgs extends Function {
	public GetAllParentOrgs() {
		numberOfParameters = 1;
	}

	public void run(Stack stack) throws ParseException
	{
		checkStack(stack); // check the stack

		stack.push(perform(stack.pop()));
	}

	protected Org[] perform(Object param1) throws ParseException {
		if (param1 == null) {
			return new Org[0];
		}
		//组织机构对象
		if (param1 instanceof Org[]) {
			Org[] orgs = (Org[]) param1;
			List result = new ArrayList();
			for (int i = 0; i < orgs.length; i++) {
			    Org org = orgs[i];
			    Org parent = org.getParent();
			    if (parent !=null && !result.contains(parent)) {
			        result.add(parent);
			    }
			    while(parent != null) {
			        Org p = parent.getParent();
			        if (p != null && !result.contains(p)) {
			            result.add(p);
			        }
			        parent = p;
			    }
            }
		    
			return (Org[]) result.toArray(new Org[result.size()]);
		}
		throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName());
	}
}